<?php

/**
 * @author squallcs12
 * @copyright 2010
 */

?> 
<form method="get" action="">
    <label>Host</label><input type="text" name="host" id="host" value="localhost" />
    <label>Database</label><input type="text" name="db" id="db" />
    <label>User</label><input type="text" name="user" id="user" value="root" />
    <label>Pass</label><input type="text" name="pass" id="pass" />
    <label>Prefix length</label><input type="text" name="prefix" id="prefix" value="0" />
    <input type="submit" value="Generate" />
</form>
<style>
label{
    float: left;
    width: 150px;
    clear: left;
}
input{
    float: left;
}
input[type=submit]{
    clear: left;
    margin-left: 150px;
}
</style>
<?php
if(empty($_REQUEST['host']))
    die;

@mkdir("DbTable", 0777);
mysql_connect($_REQUEST['host'], $_REQUEST['user'], $_REQUEST['pass']);
mysql_select_db($_REQUEST['db']) or die('Can not connect to database');

$tables = getTables();
$tablePreix = getPrefix($tables);

foreach($tables as $table)
{
    $cols = getCols($table);
    $fields = array();
    foreach($cols as $col)
        $fields[] = $col[0];
    $fieldPrefix = strlen(getPrefix($fields));
    $pris = array();
    foreach($cols as $col)
        if($col[3] === "PRI")
            $pris[] = $col;
    $str1 = "";
    foreach($cols as $col)
        $str1 .= "\t\tif(isset(\$item->_m".makeVariable($col[0], $fieldPrefix).")) \$data['{$col[0]}'] = \$item->_m".makeVariable($col[0], $fieldPrefix).";\n";
    $str2 = "";
    foreach($cols as $col)
        $str2 .= "\t\t\tif(isset(\$row->{$col[0]}))\$item->_m".makeVariable($col[0], $fieldPrefix)." = \$row->{$col[0]};\n";
    $str3 = "";
    foreach($pris as $col)
        $str3 .= "\t\t\t\$old->_m".makeVariable($col[0], $fieldPrefix)." === null ? \$key[] = '{$col[0]} is NULL' : \$key['{$col[0]} = ?'] =  \$old->_m".makeVariable($col[0], $fieldPrefix).";\n";
    $str4 = "";
    foreach($cols as $col)
        $str4 .= "\tpublic \$_m". makeVariable($col[0], $fieldPrefix).";\n";
    $str5 = "";
    foreach($cols as $col)
        $str5 .= "\tpublic function get". makeVariable($col[0], $fieldPrefix)."(){\n\t\treturn \$this->_m". makeVariable($col[0], $fieldPrefix).";\n\t}\n\tpublic function set".makeVariable($col[0], $fieldPrefix)."(\$value){\n\t\t\$this->_m". makeVariable($col[0], $fieldPrefix)." = \$value;\n\t\treturn \$this;\n\t}\n";
    $className = makeVariable($table, $_REQUEST['prefix']);
    
    $content = "class Application_Model_{$className}
{
\tprotected \$_dbTable;
$str4
$str5

\tpublic function setDbTable(\$dbTable){
\t\tif (is_string(\$dbTable))
\t\t\t\$dbTable = new \$dbTable();
\t\tif (!\$dbTable instanceof Zend_Db_Table_Abstract)
\t\t\tthrow new Exception('Invalid table data gateway provided');
\t\t\$this->_dbTable = \$dbTable;
\t\treturn \$this;
\t}
\tpublic function getDbTable(){
\t\tif (null === \$this->_dbTable)
\t\t\t\$this->setDbTable('Application_Model_DbTable_{$className}');
\t\treturn \$this->_dbTable;
\t}
\tpublic function save(Application_Model_{$className} \$old = null){
\t\t\$item = \$this;
\t\t\$data = array();
$str1
\t\tif(\$old === null)
\t\t\t\$this->getDbTable()->insert(\$data);
\t\telse{
\t\t\t\$key = array();
$str3
\t\t\t\$this->getDbTable()->update(\$data, \$key);
\t\t}
\t}
\tpublic function delete(){
\t\t\$item = \$this;
\t\t\$old = \$item;
\t\t\$key = array();
$str3
\t\t\$this->getDbTable()->delete(\$key);
\t}
\tpublic function fetchAll(\$where = null, \$order = null, \$count = null, \$offset = null){
\t\t\$resultSet = \$this->getDbTable()->fetchAll(\$where, \$order, \$count, \$offset);
\t\t\$entries   = array();
\t\tforeach (\$resultSet as \$row) {
\t\t\t\$item = new Application_Model_{$className}();
$str2
\t\t\t\$entries[] = \$item;
\t\t}
\t\treturn \$entries;
\t}
}\n";
    $content2 = "<?php
class Application_Model_DbTable_{$className} extends Zend_Db_Table_Abstract
{
\tprotected \$_name = '{$table}';
}";
    file_put_contents("{$className}.php", "<?php\n".$content);
    file_put_contents("DbTable\\{$className}.php", $content2);
}

echo "DONE";
function makeVariable($field, $start)
{
    $field = substr($field, $start);
    $parts = explode('_', $field);
    $parts2 = array();
    foreach($parts as $part)
        if($part)
            $parts2[] = ucfirst($part);
    return implode('', $parts2);   
}
function getCols($table)
{
    $sql = "SHOW COLUMNS FROM `$table`";
    $query = mysql_query($sql);
    while($result = mysql_fetch_row($query))
        $tables[] = $result;
    return $tables;
}
function getTables()
{
    $sql = 'SHOW TABLES';
    $query = mysql_query($sql);
    while($result = mysql_fetch_row($query))
        $tables[] = $result[0];
    return $tables;
}
function getPrefix($array)
{
	if(count($array) == 1)
		return "";
    $i = 0;
    $prefix = "";
    while(true)
    {
		if(!isset($array[0][$i]))
			return $prefix;
        $c = $array[0][$i];
        foreach($array as $item)
            if(!isset($item[$i]) || $item[$i] != $c)
                return $prefix;
        $prefix .= $c;
        $i++;
    }
    return $prefix;
}
function d(){
    ob_start();
    print_r(func_get_args());
    $content = ob_get_clean();
    echo '<pre>';
    echo htmlspecialchars($content);
    echo '</pre>';
}

?>